package net.xuele.learn.unsafe;

import org.jctools.queues.MpmcArrayQueue;
import org.junit.Test;
import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * @Author: yubo
 * @date: 20:30 2020/8/24
 * @Description: 类描述
 */

public class TestUnsafe {

    private static int byteArrayBaseOffset;

    private static int ARRAY_ELEMENT_SHIFT;

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        Unsafe UNSAFE = (Unsafe) theUnsafe.get(null);
        System.out.println(UNSAFE);

        int[] data = new int[16];
        System.out.println(Arrays.toString(data));
        byteArrayBaseOffset = UNSAFE.arrayBaseOffset(int[].class);
        System.out.println(byteArrayBaseOffset);
        UNSAFE.putInt(data, Long.valueOf(byteArrayBaseOffset + 1),  1);
        UNSAFE.putInt(data, Long.valueOf(byteArrayBaseOffset + 5),  5);
        System.out.println(Arrays.toString(data));
        // 简单点理解，64位系统中有压缩指针占用4个字节，没有压缩指针占用8个字节
        int scale = UNSAFE.arrayIndexScale(int[].class);
        if (4 == scale) {
            System.out.println("----------");
            ARRAY_ELEMENT_SHIFT = 2;
        } else if (8 == scale) {
            ARRAY_ELEMENT_SHIFT = 3;
        } else {
            throw new IllegalStateException("未知指针的大小");
        }

        long index = calcElementOffset(0, data.length - 1);
        System.out.println("===============" + index);
//        UNSAFE.putOrderedObject(data, index, (byte) 7);
        System.out.println(Arrays.toString(data));
        Object objectVolatile = UNSAFE.getObjectVolatile(data, index);
        System.out.println(objectVolatile);

    }

    private static long calcElementOffset(long index, long mask) {
        // index & mask 相当于取余数，表示index到达数组尾端了从头开始
        return byteArrayBaseOffset + ((index & mask) << ARRAY_ELEMENT_SHIFT);
    }

    @Test
    public void test() {

    }
}
